package com.test.platform.service.developer;

import com.test.platform.dao.DeveloperInfoMapper;
import com.test.platform.model.DeveloperInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DeveloperInfoService {
    private static final Logger logger = LoggerFactory.getLogger(DeveloperInfoService.class);

    @Autowired
    private DeveloperInfoMapper developerInfoMapper;

    @Value("${developer.info.update.enabled:false}")
    private boolean developerInfoUpdateEnabled;
    
    public List<DeveloperInfo> getAllDeveloperInfos() {
        return developerInfoMapper.findAll();
    }
    
    public DeveloperInfo getDeveloperInfoById(Integer id) {
        return developerInfoMapper.findById(id);
    }
    
    public List<DeveloperInfo> getDeveloperInfosByOwner(String owner) {
        return developerInfoMapper.findByOwner(owner);
    }

    public List<DeveloperInfo> getDeveloperInfosByName(String name) {
        return developerInfoMapper.findByName(name);
    }

    // 修改现有方法，支持模糊搜索
    public List<DeveloperInfo> getDeveloperInfosByOwnerAndName(String owner, String name) {
        return developerInfoMapper.findByOwnerAndName(owner, name);
    }
    
    public boolean createDeveloperInfo(DeveloperInfo developerInfo) {
        return developerInfoMapper.insert(developerInfo) > 0;
    }
    
    @Transactional
    public boolean updateDeveloperInfo(DeveloperInfo developerInfo) {
        if (!developerInfoUpdateEnabled) {
            return false;
        }
        
        try {
            return developerInfoMapper.update(developerInfo) > 0;
        } catch (Exception e) {
            logger.error("更新开发者信息失败: {}", e.getMessage());
            throw e;
        }
    }

    public boolean toggleUpdateEnabled() {
        developerInfoUpdateEnabled = !developerInfoUpdateEnabled;
        logger.info("开发者信息更新功能状态: {}", developerInfoUpdateEnabled ? "启用" : "禁用");
        return developerInfoUpdateEnabled;
    }

    public boolean isUpdateEnabled() {
        return developerInfoUpdateEnabled;
    }
    
    // 将 deleteDeveloperInfo 改名为 deleteById 以保持一致性
    public boolean deleteById(Integer id) {
        return developerInfoMapper.deleteById(id) > 0;
    }

    @Transactional
    public boolean deleteByIds(List<Integer> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return false;
            }
            return developerInfoMapper.deleteByIds(ids) > 0;
        } catch (Exception e) {
            logger.error("批量删除开发者信息失败: ids={}", ids, e);
            return false;
        }
    }
    
}